<?php
/**
 * Contact controller. Provides contact form functionality
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Contact Module
 * @subpackage Controller
 * @license  New BSD License
 *
 */
class contact_IndexController extends Bel_Controller{

	/**
	 * Contact form will send messages to this address
	 *
	 */
	const EMAIL_TO = 'email@to.com';
	
	/**
	 * Initialization
	 *
	 */
	public function init(){
		parent::init();
		$this->_formdata = new Zend_Session_Namespace ( 'formdata' );
	}
	
    /**
     * Displays contact form
     *
     */
    public function indexAction(){
        $form = new Bel_Forms_Builder('contact_form','/contact/index/send');   

        if($this->_formdata->values){			
			$form->populateForm($this->_formdata->values);
			$this->_formdata->unsetAll();			
			
			//get messages in case of error
			$this->view->assign('messages', $this->_messages->getMessages());
		}        
		
		
        $this->view->assign('form',$form);     
        $this->view->display('contact/contact.tpl');
    }

    /**
     * Sends message
     *
     */
    public function sendAction(){
		
    	$error = false;
    	
    	$request = $this->_request->getParams();
    		
    	if(!$this->validateCaptcha($request)){
			$this->_messages->setMessage('Wrong captcha field','error','captcha');
			$error = true;
		}
    	
    	if($this->_validator->validate('contact_form',$request) && !$error){
            $mailer = new Bel_Mailer();
            $mailer->addTo (self::EMAIL_TO );
            $mailer->clearFrom();
            $mailer->setFrom($request['contact_email'], $request['contact_name']);
            $mailer->addHeader('Reply-To',$request['contact_email']);
            $mailer->setSubject($request['contact_subject']);
            $mailer->setBodyHtml ( $request['contact_body'] );
            $mailer->send ();
            $this->_messages->setMessage('Thank You! Message has been sent');
   		
    	}else{
    		foreach ( $this->_validator->getErrors () as $field=>$error ) {
				$this->_messages->setMessage ( $error, 'error' , $field);
			}			
			unset($request['captcha']);					
			$this->_formdata->values = $request;			
    	}   	

        $this->_redirect ( '/contact/' );
    }

    
    /**
	 * Validates catcha field
	 *
	 * @param unknown_type $request
	 * @return bool
	 */
	public function validateCaptcha($request) {
		
		$captcha = new Zend_Captcha_Image(array(	
   			 'name' => 'captcha',		
    		 'wordLen' => 6,
    		 'timeout' => 300,
		));
		
		if($captcha->isValid($request['captcha']['input'],$request)){
			return true;
		}else{
			return false;
		}
	}
    

}
